//
//  EmotionTextView.swift
//  EmotionKeyboard
//
//  Created by 史亚洲 on 16/2/6.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class EmotionTextView: UITextView {
     func insetText(em: Emotion){
        
        if em.isEmpty{
            
            print("点击的是空表情");
            return;
        }
        
        if em.isDelete{
            
            //回删操作
            deleteBackward()
            return;
        }
        
        if em.code != nil{
            //点击的是 emoji表情
           replaceRange(selectedTextRange!, withText: em.emojiStr ?? "")
            return;
        }
        
        //点击的是图片
        //如何将图片输入到 textView当中
        //附件类
        let imageText=EmotionAttachment.emotionImageToAttributeString(em, font: font!)
        
        //替换之前记录之前选中的位置
        let range=selectedRange
        
        //将包含的图片的属性字符串替换到textView.attribute
        let strM=NSMutableAttributedString(attributedString: attributedText)
        
        //替换属性字符串
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        //设置属性字符串
        attributedText=strM
        
        //恢复光标位置
        selectedRange=NSRange(location: range.location+1, length: 0)
        
        //主动适应代理调用协议方法
        delegate?.textViewDidChange?(self)
        
        
    }
    
    //将属性文本转换为纯文本
    func fullText() -> String{
        
        var strM=String()
        attributedText.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: []) { (dict, range, _) -> Void in
            //如果属性中包含了 NSAttachment这个key 就意味中 是图片
            if let attachment=dict["NSAttachment"] as? EmotionAttachment{
                
                
                strM += (attachment.chs ?? "")
                
                
                
            }else{
                
                let subStr=(self.text as NSString).substringWithRange(range)
                strM += subStr
                
                
            }
        }
        
        return strM
        
    }


}
